package com.example.application.views.petSupplier;

import com.example.application.bean.*;
import com.example.application.views.main.MainView;
import com.example.application.views.supplier.SupplierUri;
import com.example.application.views.util.DialogUtil;
import com.example.application.views.util.MyHttpClientUtil;
import com.example.application.views.util.ShowAllInfosUtil;
import com.example.page.PageComponent;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.crud.BinderCrudEditor;
import com.vaadin.flow.component.crud.Crud;
import com.vaadin.flow.component.crud.CrudEditor;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.gridpro.GridPro;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.converter.StringToDoubleConverter;
import com.vaadin.flow.router.Route;

import java.util.stream.Stream;

@Route(value = "petSupplier", layout = MainView.class)
public class PetSupplierView extends Div {

    private GridPro<SupGoods> grid = new GridPro<>();
    private Crud<SupGoods> crud = new Crud<>(SupGoods.class, grid, createSupGoodsEditor());

    private String id = "2";


    private int curPage = 1;
    private int pageSize = 2;
    private int tolNum;
    private int tolPage;
    private ObjectMapper mapper = new ObjectMapper();

    private TextField name;
    private TextField type;
    private TextField material;
    private TextField applicable;
    private TextField exclusive;
    private TextField packingSize;
    private TextField flavor;
    private TextField function;
    private TextField origin;
    private DatePicker dateOfPro;
    private TextField expDate;
    private TextField explain;
    private TextField price;
    private TextField pic;

    public PetSupplierView(){

        User user = (User) UI.getCurrent().getSession().getAttribute("user");
        if (user == null){

        }else if("供应商管理员".equals(user.getIdentity())){
            this.init();
        }else{
            DialogUtil.adminAuthority();
        }

    }

    private CrudEditor<SupGoods> createSupGoodsEditor() {
        name = new TextField("商品名");
        type = new TextField("种类");
        material = new TextField("材质");
        applicable = new TextField("适用规格");
        exclusive = new TextField("专属规格");
        packingSize = new TextField("包装规格");
        flavor = new TextField("口味");
        function = new TextField("特殊功用");
        origin = new TextField("产地");
        dateOfPro = new DatePicker("出厂日期");
        expDate = new TextField("保质期");
        explain = new TextField("特色说明");
        price = new TextField("价格");
        pic = new TextField("图片");
        FormLayout form = new FormLayout(name, type, material, applicable, exclusive, packingSize, flavor, function, origin, dateOfPro, expDate, explain, price, pic);

        Binder<SupGoods> binder = new Binder<>(SupGoods.class);
        binder.bind(name, SupGoods::getName, SupGoods::setName);
        binder.bind(type, SupGoods::getType, SupGoods::setType);
        binder.bind(material, SupGoods::getMaterial, SupGoods::setMaterial);
        binder.bind(applicable, SupGoods::getApplicable, SupGoods::setApplicable);
        binder.bind(exclusive, SupGoods::getExclusive, SupGoods::setExclusive);
        binder.bind(packingSize, SupGoods::getPackingSize, SupGoods::setPackingSize);
        binder.bind(flavor, SupGoods::getFlavor, SupGoods::setFlavor);
        binder.bind(function, SupGoods::getFunction, SupGoods::setFunction);
        binder.bind(origin, SupGoods::getOrigin, SupGoods::setOrigin);
        binder.bind(dateOfPro, SupGoods::getDateOfPro, SupGoods::setDateOfPro);
        binder.bind(expDate, SupGoods::getExpDate, SupGoods::setExpDate);
        binder.bind(explain, SupGoods::getExplain, SupGoods::setExplain);
        binder.forField(price).withConverter(new StringToDoubleConverter("请输入数字")).bind("price");
        binder.bind(pic, SupGoods::getPic, SupGoods::setPic);

        return new BinderCrudEditor<>(binder, form);
    }


    private void createGridLayout(SplitLayout splitLayout) {
        Div wrapper = new Div();
        wrapper.setId("grid-wrapper");
        wrapper.setWidthFull();
        PageComponent pageComponent = new PageComponent(curPage, pageSize, PetSupplierView.this.tolNum, PetSupplierView.this.tolPage) {
            @Override
            protected void pageNext() {
                PetSupplierView.this.curPage = this.curPage;
                updateForm();
                init();
            }

            @Override
            protected void pagePrevious() {
                PetSupplierView.this.curPage = this.curPage;
                updateForm();
                init();
            }

            @Override
            protected void gotoPage() {

            }

            @Override
            protected void firstPage() {
                PetSupplierView.this.curPage = 1;
                updateForm();
                init();
            }

            @Override
            protected void lastPage() {
                PetSupplierView.this.curPage = this.tolPage;
                updateForm();
                init();
            }

            @Override
            protected void selectPage() {


            }
        };
        pageComponent.components.add(crud);
        pageComponent.init();
        splitLayout.addToPrimary(pageComponent);
    }

    private void updateForm(){
        ResultBean<PageBean> resultBean = ShowAllInfosUtil.showInfos(PetSupplierUri.PET_SUP_ALL + id, curPage, pageSize,
                SupGoods.class);
        grid.setItems(resultBean.getT().getDatas());

        tolNum = resultBean.getT().getTolNum();

        tolPage = resultBean.getT().getTolPage();
    }

    private void editItem(){
        name.setEnabled(false);
        type.setEnabled(false);
        material.setEnabled(false);
        applicable.setEnabled(false);
        exclusive.setEnabled(false);
        packingSize.setEnabled(false);
        flavor.setEnabled(false);
        function.setEnabled(false);
        origin.setEnabled(false);
        dateOfPro.setEnabled(false);
        expDate.setEnabled(false);
    }

    private void addItem(){
        name.setEnabled(true);
        type.setEnabled(true);
        material.setEnabled(true);
        applicable.setEnabled(true);
        exclusive.setEnabled(true);
        packingSize.setEnabled(true);
        flavor.setEnabled(true);
        function.setEnabled(true);
        origin.setEnabled(true);
        dateOfPro.setEnabled(true);
        expDate.setEnabled(true);
    }

    public void init(){
        crud.addSaveListener(e -> {
            SupGoods supGoods = e.getItem();
            if(supGoods.getId() != null){
                try {
                    supGoods.setExplain(explain.getValue());
                    supGoods.setPrice(Double.parseDouble(price.getValue()));
                    supGoods.setPic(pic.getValue());

                    String json = MyHttpClientUtil.httpPut(PetSupplierUri.PET_SUP_UPDATE, supGoods, "utf-8");
                    JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, String.class);
                    ResultBean resultBean = mapper.readValue(json, javaType);

                    if(resultBean.getCode() != 0){
                        UI.getCurrent().getPage().executeJs("alert('更新成功');window.location.href='http://localhost:8080/petSupplier'");
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('更新失败')");
                    }

                }catch (Exception exception){
                    exception.printStackTrace();
                }

            }else {
                try {
                    supGoods.setName(name.getValue());
                    supGoods.setType(type.getValue());
                    supGoods.setMaterial(material.getValue());
                    supGoods.setApplicable(applicable.getValue());
                    supGoods.setExclusive(exclusive.getValue());
                    supGoods.setPackingSize(packingSize.getValue());
                    supGoods.setFlavor(flavor.getValue());
                    supGoods.setFunction(function.getValue());
                    supGoods.setOrigin(origin.getValue());
                    supGoods.setDateOfPro(dateOfPro.getValue());
                    supGoods.setExpDate(expDate.getValue());

                    supGoods.setSupId(5);

                    supGoods.setExplain(explain.getValue());
                    supGoods.setPrice(Double.parseDouble(price.getValue()));
                    supGoods.setPic(pic.getValue());

                    Supplier supplier = new Supplier();
                    supplier.setId(2);
                    supGoods.setSupplier(supplier);

                    Store store = new Store();
                    store.setId(3);
                    supGoods.setStore(store);

                    String json = MyHttpClientUtil.httpPost(PetSupplierUri.PET_SUP_ADD, supGoods, "utf-8");
                    JavaType javaType = mapper.getTypeFactory().constructParametricType(ResultBean.class, String.class);
                    ResultBean resultBean = mapper.readValue(json, javaType);

                    if(resultBean.getCode() != 0){
                        UI.getCurrent().getPage().executeJs("alert('添加成功');window.location.href='http://localhost:8080/petSupplier'");
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('添加失败')");
                    }
                }catch (Exception exception){
                    exception.printStackTrace();
                }


            }
        });

        crud.addDeleteListener(e -> {
            SupGoods supGoods = e.getItem();

            try {
                if(supGoods.getId() != null){
                    String msg = MyHttpClientUtil.httpDelete(PetSupplierUri.PET_SUP_DELETE, supGoods.getId(), "utf-8");
                    ResultBean resultBean = mapper.readValue(msg, ResultBean.class);
                    if(resultBean.getCode() != 0){
                        UI.getCurrent().getPage().executeJs("alert('删除成功');window.location.href='http://localhost:8080/petSupplier'");
                    }else {
                        UI.getCurrent().getPage().executeJs("alert('删除失败');");
                    }
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }

        });

        crud.addEditListener(e -> {
            editItem();
        });

        crud.addNewListener(e -> {
            addItem();
        });

        Crud.addEditColumn(grid);
        this.updateForm();

        if(this.tolNum == 0){
            this.add(new Text("没有数据"));
        }else{
            SplitLayout splitLayout = new SplitLayout();
            splitLayout.setSizeFull();
            createGridLayout(splitLayout);

            HorizontalLayout horizontalLayout = new HorizontalLayout();
            Button button = new Button("查看统计");

            button.addClickListener((e) -> {
                UI.getCurrent().navigate("count");
            });
            horizontalLayout.add(button);

            HorizontalLayout layout = new HorizontalLayout();

            grid.addColumn(SupGoods::getName).setHeader("商品名");
            grid.addColumn(SupGoods::getType).setHeader("类型");
            grid.addColumn(SupGoods::getMaterial).setHeader("材质");
            grid.addColumn(SupGoods::getApplicable).setHeader("适用规格");
            grid.addColumn(SupGoods::getExclusive).setHeader("专属规格");
            grid.addColumn(SupGoods::getPackingSize).setHeader("包装规格");
            grid.addColumn(SupGoods::getFlavor).setHeader("口味");
            grid.addColumn(SupGoods::getFunction).setHeader("特殊功用");
            grid.addColumn(SupGoods::getOrigin).setHeader("产地");
            grid.addColumn(SupGoods::getDateOfPro).setHeader("生产日期");
            grid.addColumn(SupGoods::getExpDate).setHeader("保质期");
            grid.addColumn(SupGoods::getSupId).setHeader("供货商ID");
            grid.addEditColumn(SupGoods::getExplain).text(SupGoods::setExplain).setHeader("特色说明");
            grid.addEditColumn(SupGoods::getPrice).text((item, newValue)->{
                item.setPrice(Double.parseDouble(newValue));
            }).setHeader("价格");
            grid.addEditColumn(SupGoods::getPic).text(SupGoods::setPic).setHeader("图片");

            layout.add(crud);
            this.add(horizontalLayout, layout);
            add(splitLayout);
        }
    }

}